package com.keta.foundation.controller;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.keta.foundation.dataFilter.DataFilter;
import com.keta.foundation.dataFilter.DynamicSpecifications;
import com.keta.foundation.dataFilter.DataFilter.Operator;
import com.keta.foundation.entity.Dict;
import com.keta.foundation.entity.Module;
import com.keta.foundation.log.Log;
import com.keta.foundation.log.LogUtil;
import com.keta.foundation.service.DictService;
import com.keta.foundation.util.dwz.AjaxObject;
import com.keta.foundation.util.dwz.Page;

@Controller
@RequestMapping("/dict")
public class DictController {
	
	private static final String DICT_LIST_DICT = "dict/list_dict";
	private static final String DICT_LIST_ITEM = "dict/list_item";
	private static final String DICT_CREATE_DICT = "dict/create_dict";
	private static final String DICT_CREATE_ITEM = "dict/create_item";
	private static final String DICT_EDIT_DICT = "dict/edit_dict";
	private static final String DICT_EDIT_ITEM = "dict/edit_item";
	private static final String DICT_LOOKUP_PARENT = "dict/lookup_parent";
	
	
	@Autowired
	private DictService dictService;

	/**
	 * 字典列表入口
	 */
	@RequestMapping("/list_dict")
	public String list_dict(Page page,Model model,HttpServletRequest request){
		DataFilter filter = new DataFilter("type", Operator.EQ, Dict.TYPE_DICT);
		Specification<Dict> specifications = DynamicSpecifications.byDataFilter(request, Dict.class,filter);
		page.setOrderDirection(Direction.ASC.toString());
		page.setOrderField("priority");
		
		List<Dict> dicts = dictService.getAll(specifications,page);
		model.addAttribute("page", page);
		model.addAttribute("dicts", dicts);
		return DICT_LIST_DICT;
	}
	
	
	/**
	 * 字典列表入口
	 */
	@RequestMapping("/list_item/{dictId}")
	public String list_item(@PathVariable Long dictId,Page page,Model model,HttpServletRequest request){
		DataFilter filterType = new DataFilter("type", Operator.EQ, Dict.TYPE_ITEM);
		DataFilter filterDict = new DataFilter("parent.id", Operator.EQ, dictId);
		Specification<Dict> specifications = DynamicSpecifications.byDataFilter(request, Dict.class,filterType,filterDict);
		page.setOrderDirection(Direction.ASC.toString());
		page.setOrderField("priority");
		
		List<Dict> dicts = dictService.getAll(specifications,page);
		model.addAttribute("dictId", dictId);
		model.addAttribute("page", page);
		model.addAttribute("dicts", dictService.treeToList(dicts));
		return DICT_LIST_ITEM;
	}
	
	
	/**
	 * 打开添加字典主题页面
	 */
	@RequestMapping(value="/createDict",method = RequestMethod.GET)
	public String perCreateDict(){
		
		return DICT_CREATE_DICT;
	}
	
	/**
	 * 打开添加字典项页面
	 */
	@RequestMapping(value="/createItem/{dictId}",method = RequestMethod.GET)
	public String perCreateItem(@PathVariable Long dictId,Model model){
		
		model.addAttribute("dictId", dictId);
		return DICT_CREATE_ITEM;
	}
	
	
	/**
	 * 创建字典主题入口
	 */
	@Log(message="添加字典{0}")
	@RequestMapping(value="/createDict",method = RequestMethod.POST)
	public @ResponseBody String createDict(@Valid Dict dict){
		dict.setType(Dict.TYPE_DICT);
		dictService.saveOrUpdate(dict);
		LogUtil.putArgs(new Object[] { dict.getCode() });
		return AjaxObject.newOk("字典主题添加成功！").toString();
	}
	
	/**
	 * 创建字典项入口
	 */
	@Log(message="添加字典项{0}")
	@RequestMapping(value="/createItem",method = RequestMethod.POST)
	public @ResponseBody String createItem(@Valid Dict item,Long dictId){
		item.setType(Dict.TYPE_ITEM);
		dictService.saveOrUpdateItem(item,dictId);
		LogUtil.putArgs(new Object[] { item.getCode() });
		return AjaxObject.newOk("字典项添加成功！").toString();
	}
	
	
	/**
	 * 打开编辑字典主题页面
	 */
	@RequestMapping(value="/editDict/{dictId}",method = RequestMethod.GET)
	public String perEditDict(@PathVariable Long dictId,Model model){
		Dict dict  = dictService.getById(dictId);
		model.addAttribute("dict", dict);
		return DICT_EDIT_DICT;
	}
	
	/**
	 * 打开编辑字典项页面
	 */
	@RequestMapping(value="/editItem/{dictId}/{itemId}",method = RequestMethod.GET)
	public String perEditItem(@PathVariable Long dictId,@PathVariable Long itemId,Model model){
		Dict item  = dictService.getById(itemId);
		model.addAttribute("item", item);
		model.addAttribute("dictId", dictId);
		return DICT_EDIT_ITEM;
	}
	
	
	/**
	 * 编辑字典主题入口
	 */
	@Log(message="编辑字典主题{0}")
	@RequestMapping(value="/editDict",method = RequestMethod.POST)
	public @ResponseBody String editDict(@Valid Dict dict){
		dict.setType(Dict.TYPE_DICT);
		dictService.saveOrUpdate(dict);
		LogUtil.putArgs(new Object[] { dict.getCode() });
		return AjaxObject.newOk("字典主题编辑成功！").toString();
	}
	
	
	/**
	 * 编辑字典项入口
	 */
	@Log(message="编辑字典项{0}")
	@RequestMapping(value="/editItem",method = RequestMethod.POST)
	public @ResponseBody String editItem(@Valid Dict dict){
		dict.setType(Dict.TYPE_ITEM);
		dictService.saveOrUpdate(dict);
		LogUtil.putArgs(new Object[] { dict.getCode() });
		return AjaxObject.newOk("字典项编辑成功！").toString();
	}
	
	@Log(message = "删除了字典主题{0}")
	@RequestMapping(value = "/deleteDict")
	public @ResponseBody String deleteDict(Long[] ids) {
		String logInfo = "";
		for (Long id : ids) {
			Dict dict = dictService.getById(id);
			logInfo+=dict.getCode();
			dictService.delete(dict);
		}

		LogUtil.putArgs(new Object[] { logInfo });
		return AjaxObject.newOk("删除字典主题成功!").setCallbackType("").toString();
	}
	
	@Log(message = "删除了字典项{0}")
	@RequestMapping(value = "/deleteItem")
	public @ResponseBody String deleteItem(Long[] ids) {
		String logInfo = "";
		for (Long id : ids) {
			Dict dict = dictService.getById(id);
			logInfo+=dict.getCode();
			dictService.delete(dict);
		}

		LogUtil.putArgs(new Object[] { logInfo });
		return AjaxObject.newOk("删除字典项成功!").setCallbackType("").toString();
	}
	
	
	@RequestMapping(value = "/lookupParent/{dictId}")
	public  String lookupParent(@PathVariable Long dictId,Model model) {
		List<Dict> items = dictService.getDictItem(dictId);
		model.addAttribute("items", items);
		return DICT_LOOKUP_PARENT;
	}
	
	
	
	
	
}
